//
//  HKWebViewContainer.m
//  HKTimeKitApp
//
//  Created by huzhaoke1 on 2023/5/26.
//

#import "HKWebViewContainer.h"
#import<WebKit/WebKit.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import <Reachability/Reachability.h>
#import "UIView+properties.h"
#import "HKCommonDefine.h"
#import "HKUser.h"
#import "HTTPURL.h"
#import "HKHeartBeatViewController.h"
#import "HKRequestDefine.h"
#import "HKLoadingView.h"
#import "HKToastView.h"
#import "HKCalendarAndLocalNotificationHandler.h"
#import "HKAvVideoRecorder.h"
#import "HKWebViewContainer.h"
#import "AppDelegate.h"
#import "ZWKURLHandler.h"
#import "NSString+KSURLEncoded.h"
#import <JavaScriptCore/JavaScriptCore.h>
#import "THRecorderController.h"
#import "WebViewJavascriptBridge.h"


static NSString *kKSGetTokenStr = @"getToken";
static NSString *kKSLogoutStr = @"logout";
static NSString *kKSGetUserInfoStr = @"getUserInfo";
static NSString *kKSClearCacheFinishStr = @"clearCacheFinish";
static NSString *kKSGoBackStr = @"goBack";
static NSString *kKStoHeartStr = @"toHeart";
static NSString *kKSOpenPictureSelectStr = @"openPictureSelect";
static NSString *kKSOpenVideoSelectStr = @"openVideoSelect";
static NSString *kKSGotoPictureSelectStr = @"gotoPictureSelect";
static NSString *kKSGotoRecordVideoStr = @"gotoRecordVideo";

static NSString *kKSOpenSandianPictureSelect = @"openSandianPictureSelect";
static NSString *kKSGotoSandianPictureSelect = @"gotoSandianPictureSelect";

static NSString *kKSAddAlarmStr = @"addAlarm";
static NSString *kKSPlayRecordStr = @"playRecord";
static NSString *kKSStartRecordStr = @"startRecord";
static NSString *kKSPauseRecordStr = @"pauseRecord";
static NSString *kKSStopRecordStr = @"stopRecord";

static NSString *kKSOpenFileSelect = @"openFileSelect";
static NSString *kKopenCommonPictureSelect = @"openCommonPictureSelect";
static NSString *kKgotoCommonPictureSelect = @"gotoCommonPictureSelect";

@implementation HKScriptMessageDelegate

- (instancetype)initWithDelegate:(id<WKScriptMessageHandler>)scriptDelegate {
    self = [super init];
    if (self) {
        _scriptDelegate = scriptDelegate;
    }
    return self;
}

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    [self.scriptDelegate userContentController:userContentController didReceiveScriptMessage:message];
}

@end


@interface HKWebViewContainer ()<UIImagePickerControllerDelegate, WKScriptMessageHandler,
UINavigationControllerDelegate,
UIDocumentPickerDelegate,
THRecorderControllerDelegate,
WKNavigationDelegate,
WKUIDelegate>


@property (nonatomic, strong) HKScriptMessageDelegate *scripteDelegate;
@property (nonatomic, strong) HKCalendarAndLocalNotificationHandler *calenddarAndLocationNotificationHandler;
//@property (nonatomic, strong) HKAvVideoRecorder *recorder;

@property (nonatomic, assign) BOOL isSandian;
@property (nonatomic, assign) BOOL isCommon;
@property (nonatomic,strong)THRecorderController *recorderController;

@property (nonatomic, assign) BOOL isLimitType;
@property (nonatomic, copy) NSArray<NSString *> *limitTypes;
@property (nonatomic, assign) BOOL isUploadFile;

@property (nonatomic, strong) UIDocumentPickerViewController *documentPicker;

///记录下重定向之前的url
@property (nonatomic, copy) NSString *redirectUrl;
@property (nonatomic, weak) ZWKURLHandler *urlHandler;
@property (nonatomic, strong) NSURLRequest *request;
@property WebViewJavascriptBridge* bridge;
@property (nonatomic, assign) BOOL selectFileUploadPhoto;
@end

@implementation HKWebViewContainer

- (void)dealloc {
    //控制器销毁的时候,离线包的网络请求也销毁
    [self.urlHandler removeAllActivitiesSchemeTasks];
    NSLog(@"dealloc --------- %@",NSStringFromClass(self.class));
}

- (THRecorderController *)recorderController{
    if (!_recorderController) {
        _recorderController = [[THRecorderController alloc] init];
        _recorderController.delegate = self;
    }
    return _recorderController;
}
 
- (instancetype)init {
    if (self = [super init]) {        
        self.wkWebView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, HKScreenWidth, HKScreenHeight)];
        self.wkWebView.UIDelegate = self;
        self.wkWebView.navigationDelegate = self;
        self.wkWebView.configuration.processPool = [[WKProcessPool alloc] init];
        self.wkWebView.configuration.mediaTypesRequiringUserActionForPlayback = WKAudiovisualMediaTypeNone;
        self.wkWebView.configuration.allowsInlineMediaPlayback = YES;
        self.wkWebView.configuration.suppressesIncrementalRendering = YES;
        NSString * consoleLog = @"console.log = (function(oriLogFunc){return function(str){oriLogFunc.call(console,str);window.webkit.messageHandlers.log.postMessage(str);}})(console.log);";
        WKUserScript *userScriptLog = [[WKUserScript alloc] initWithSource:consoleLog injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:YES];
        [self.wkWebView.configuration.userContentController addUserScript:userScriptLog];
        [self.wkWebView.configuration.userContentController removeScriptMessageHandlerForName:@"bridgeTest"];
        [self.wkWebView.configuration.userContentController addScriptMessageHandler:self.scripteDelegate name:@"bridgeTest"];
        [self.wkWebView.configuration.userContentController addScriptMessageHandler:self.scripteDelegate name:@"log"];
    }
    return self;
}

-(void)loadingRequestWithUrl:(NSString *)webUrl {
    if (webUrl.length == 0) return;
    self.webUrl = webUrl;
    NSURL* url = [NSURL URLWithString:webUrl];//创建URL
    NSURLRequest* request = [NSURLRequest requestWithURL:url cachePolicy: NSURLRequestReturnCacheDataElseLoad  timeoutInterval:60];//创建NSURLRequest
    [self.wkWebView loadRequest:request];
}

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    if ([message.name isEqualToString:@"log"]) {
        NSLog(@"console.log:%@",message.body);
    }
    if ([message.name isEqualToString:@"bridgeTest"]) {
        NSString *bodyString = KSSAFE_CAST(message.body, NSString);
        NSDictionary *dic = KSSAFE_CAST([bodyString mj_JSONObject], NSDictionary);
        NSString *actionName = KSSAFE_CAST(dic[@"name"], NSString);
        if (actionName.length > 0) {
            if ([actionName isEqualToString:kKSGetTokenStr]) {
                NSLog(@"获取token");
                HKUser *user = WMglobalUser();
                NSString *jsString = [NSString stringWithFormat:@"window.setToken(\"%@\")", user.token?:@""];
                [self.wkWebView evaluateJavaScript:jsString completionHandler:^(id _Nullable data, NSError * _Nullable error) {
                    
                }];
            } else if ([actionName isEqualToString:kKSLogoutStr]) {
                logout();
            } else if ([actionName isEqualToString:kKSGetUserInfoStr]) {
                HKUser *user = WMglobalUser();
                NSMutableDictionary *tempDic = [user mj_keyValues].mutableCopy;
                [tempDic removeObjectForKey:@"token"];
                NSString *userStr = [tempDic mj_JSONString];
                NSString *jsString = [NSString stringWithFormat:@"window.setUser(\"%@\")", userStr?:@""];
                [self.wkWebView evaluateJavaScript:jsString completionHandler:^(id _Nullable data, NSError * _Nullable error) {
                }];
            } else if ([actionName isEqualToString:kKSClearCacheFinishStr]) {
                [self clearCache];
                [self closePage];
            } else if ([actionName isEqualToString:kKSGoBackStr]) {
                [self closePage];
            } else if ([actionName isEqualToString:kKStoHeartStr]) {
                [self gotoHeartBeat];
            }else if ([actionName isEqualToString:kKopenCommonPictureSelect]){
                self.isCommon = YES;
                 [self SelectPhotoAlbumVideo];
            }else if ([actionName isEqualToString:kKgotoCommonPictureSelect]){
                self.isCommon = YES;
                [self goCameraPic];
            }else if ([actionName isEqualToString:kKSOpenPictureSelectStr]) {
                [self SelectPhotoAlbumVideo];
            } else if ([actionName isEqualToString:kKSOpenVideoSelectStr]) {
                [self SelectPhotoVideo];
            } else if ([actionName isEqualToString:kKSGotoPictureSelectStr]) {
                [self goCameraPic];
            } else if ([actionName isEqualToString:kKSGotoRecordVideoStr]) {
                [self goCameraVideo];
            } else if ([actionName isEqualToString:kKSAddAlarmStr]) {
                HKCalendarModel *model = [HKCalendarModel mj_objectWithKeyValues:message];
                [self.calenddarAndLocationNotificationHandler saveCalendarAndPostLocalNotificationWithModel:model];
            } else if ([actionName isEqualToString:kKSPlayRecordStr]) {
                [self.recorderController play];
            } else if ([actionName isEqualToString:kKSStartRecordStr]) {
                [self.recorderController record];
                NSString *jsString = [NSString stringWithFormat:@"javascript:recordStartCallback(\"%@\")", [self.recorderController filePathUrl]];
                [self.wkWebView evaluateJavaScript:jsString completionHandler:^(id _Nullable data, NSError * _Nullable error) {
                }];
            } else if ([actionName isEqualToString:kKSPauseRecordStr]) {
                [self.recorderController pause];
            } else if ([actionName isEqualToString:kKSStopRecordStr]) {
                WS
                [self.recorderController stopWithCompletionHandler:^(BOOL stop , NSData *data) {
                    SS
                    NSLog(@"%@",data);
                    [self uploadRecordFileWithFileData:data];
                    
                }];
            } else if ([actionName isEqualToString:kKSOpenSandianPictureSelect]) {
                self.isSandian = YES;
                [self SelectPhotoAlbumVideo];
            } else if ([actionName isEqualToString:kKSGotoSandianPictureSelect]) {
                self.isSandian = YES;
                [self goCameraPic];
            } else if ([actionName isEqualToString:kKSOpenFileSelect]) {
                NSDictionary *data = KSSAFE_CAST(dic[@"data"], NSDictionary);
                self.isLimitType = KSSAFE_CAST(data[@"isLimitType"], NSNumber).boolValue;
                NSString *types = data[@"types"];
                self.limitTypes = [types componentsSeparatedByString:@","];
                self.isUploadFile = YES;
                [self openFileType];
            }
        }
    }
}

- (void)openFileType{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"选择文件上传" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [alert addAction:[UIAlertAction actionWithTitle:@"照片图库" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.selectFileUploadPhoto = YES;
        [self SelectPhotoAlbumVideo];
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.selectFileUploadPhoto = YES;
        [self goCameraPic];
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"选取文件" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self createDocumentPickerWithTypes:[self types]];
        [[self keyNavi] presentViewController:self.documentPicker animated:YES completion:nil];
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
 
    }]];
    [[self keyNavi] presentViewController:alert animated:YES completion:nil];
}

- (void)closePage {
    [[self keyNavi] popViewControllerAnimated:YES];
    [self loadingRequestWithUrl:self.webUrl];
}

// 进入到心跳的页面
- (void)gotoHeartBeat {
    HKHeartBeatViewController *controller = [HKHeartBeatViewController new];
    WS
    [controller setToGetFrequencyBlock:^(NSInteger frequency) {
        SS
        NSString *jsString = [NSString stringWithFormat:@"javascript:getHeartData(\"%@\")", @(frequency)];
        [self.wkWebView evaluateJavaScript:jsString completionHandler:^(id _Nullable data, NSError * _Nullable error) {
        }];
    }];
    [[self keyNavi] pushViewController:controller animated:YES];
}

// 选择相册图片
- (void)SelectPhotoAlbumVideo {
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        picker.mediaTypes = @[(NSString *)kUTTypeImage,(NSString *)kUTTypeMovie];
    }
    picker.delegate = self;
    picker.allowsEditing = NO;
    picker.videoMaximumDuration = 60;
    [[self currentViewController] presentViewController:picker animated:YES completion:nil];
}

// 选择相册视频
- (void)SelectPhotoVideo {
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        picker.mediaTypes = @[(NSString *)kUTTypeMovie];
    }
    picker.delegate = self;
    picker.allowsEditing = NO;
    picker.videoMaximumDuration = 60;
    [[self currentViewController] presentViewController:picker animated:YES completion:nil];
}

// 去拍摄照片
- (void)goCameraPic {
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        picker.mediaTypes = @[(NSString *)kUTTypeImage];
        picker.cameraDevice = UIImagePickerControllerCameraDeviceFront;
    }
    
    picker.delegate = self;
    [[self currentViewController] presentViewController:picker animated:YES completion:nil];
}

// 去拍摄视频
- (void)goCameraVideo {
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        picker.cameraDevice = UIImagePickerControllerCameraDeviceFront;
        picker.mediaTypes = @[(NSString *)kUTTypeMovie];
    }
    picker.delegate = self;
    picker.videoMaximumDuration = 60;
    [[self currentViewController] presentViewController:picker animated:YES completion:nil];
}

#pragma mark - album
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
        UIImage *tempImage = [info objectForKey:UIImagePickerControllerOriginalImage];
        if (self.isSandian) {
            [self uploadSandianImage:tempImage];
        }else if (self.isCommon){
            [self uploadCommonImage:tempImage];
        }else {
            [self uploadImage:tempImage];
        }
    } else if ([mediaType isEqualToString:(NSString *)kUTTypeMovie]) {
        NSURL *mediaURL = [info objectForKey:UIImagePickerControllerMediaURL];
        NSData *webData = [NSData dataWithContentsOfURL:mediaURL];
        [self uploadFile:webData fileName:mediaURL.pathComponents.lastObject];
    }
    [picker dismissViewControllerAnimated:YES completion:nil];
    self.isSandian = NO;
    self.isCommon = NO;
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
    self.isSandian = NO;
    self.isCommon = NO;
}

- (void)uploadSandianImage:(UIImage *)image {
    [[HKLoadingView loadingView] showLoading];
    [HTTPURL uploadImageWithPath:HKPublicSandianImagePath params:@{} img:image success:^(NSURLSessionDataTask *task, NSDictionary *successUrl) {
        [[HKLoadingView loadingView] hideLoading];
//        NSArray *data = KSSAFE_CAST(successUrl[@"data"], NSArray);
//        if (![data isKindOfClass:NSArray.class]) return;
//        NSMutableString *url = @"[".mutableCopy;
//        for (NSInteger index = 0; index < data.count; index++) {
//            [url appendFormat:@"%@", data[index]];
//            if (index != data.count - 1) {
//                [url appendString:@","];
//            }
//        }
//        [url appendString:@"]"];
//        if (url.length > 0) {
//            NSString *jsString = [NSString stringWithFormat:@"javascript:setUrl(\"%@\")", url?:@""];
//               [self.wkWebView evaluateJavaScript:jsString completionHandler:^(id _Nullable data, NSError * _Nullable error) {
//               }];
//        }
        NSString *json = [successUrl[@"data"] mj_JSONString];
        NSString *encodeString = [json ks_URLEncodedString];
        NSString *jsString = [NSString stringWithFormat:@"javascript:setUrl(\"%@\")", encodeString];
        [self.wkWebView evaluateJavaScript:jsString completionHandler:^(id _Nullable data, NSError * _Nullable error) {
        }];
    } failure:^(NSURLSessionDataTask *task,NSError *error) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [[HKToastView sharedToastView] showToast:error.domain];
        });
        [[HKLoadingView loadingView] hideLoading];
    }];
}

- (void)uploadCommonImage:(UIImage *)image{
    [[HKLoadingView loadingView] showLoading];
    [HTTPURL uploadImageWithPath:HKPublicCommonImageUrl params:@{} img:image success:^(NSURLSessionDataTask *task, NSDictionary *successUrl) {
        [[HKLoadingView loadingView] hideLoading];
        NSString *json = [successUrl[@"data"] mj_JSONString];
        NSString *encodeString = [json ks_URLEncodedString];
        NSString *jsString = [NSString stringWithFormat:@"javascript:setUrl(\"%@\")", encodeString];
        [self.wkWebView evaluateJavaScript:jsString completionHandler:^(id _Nullable data, NSError * _Nullable error) {
        }];
    } failure:^(NSURLSessionDataTask *task,NSError *error) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [[HKToastView sharedToastView] showToast:error.domain];
        });
        [[HKLoadingView loadingView] hideLoading];
    }];
}

- (void)uploadImage:(UIImage *)image {
    [[HKLoadingView loadingView] showLoading];
    NSString *path = self.selectFileUploadPhoto ? HKPublicFilePath : HKPublicImagePath;
    [HTTPURL uploadImageWithPath:path params:@{} img:image success:^(NSURLSessionDataTask *task, NSDictionary *successUrl) {
        [[HKLoadingView loadingView] hideLoading];
        NSString *json = [successUrl[@"data"] mj_JSONString];
        NSString *encodeString = [json ks_URLEncodedString];
        NSString *jsString = [NSString stringWithFormat:@"javascript:setUrl(\"%@\")", encodeString];
        [self.wkWebView evaluateJavaScript:jsString completionHandler:^(id _Nullable data, NSError * _Nullable error) {
            self.selectFileUploadPhoto = NO;
        }];
    } failure:^(NSURLSessionDataTask *task,NSError *error) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [[HKToastView sharedToastView] showToast:error.domain];
            self.selectFileUploadPhoto = NO;
        });
        [[HKLoadingView loadingView] hideLoading];
    }];
}

- (void)uploadFile:(NSData *)data
          fileName:(NSString *)fileName {
    [[HKLoadingView loadingView] showLoading];
    [HTTPURL uploadFileWithPath:HKPublicFilePath
                       fileName:fileName
                         params:@{@"token" : WMglobalUser().token?:@""} data:data success:^(NSURLSessionDataTask *task, NSDictionary *successUrl) {
        [[HKLoadingView loadingView] hideLoading];
        NSString *json = [successUrl[@"data"] mj_JSONString];
        NSString *encodeString = [json ks_URLEncodedString];
        NSString *jsString = [NSString stringWithFormat:@"javascript:setUrl(\"%@\")", encodeString];
        [self.wkWebView evaluateJavaScript:jsString completionHandler:^(id _Nullable data, NSError * _Nullable error) {
            self.selectFileUploadPhoto = NO;
        }];
    } failure:^(NSURLSessionDataTask *task,NSError *error) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [[HKToastView sharedToastView] showToast:error.domain];
            self.selectFileUploadPhoto = NO;
        });
        [[HKLoadingView loadingView] hideLoading];
    }];
}

- (void)uploadRecordFileWithFileData:(NSData *)data {
    if (!data) {
        return;
    }
    [[HKLoadingView loadingView] showLoading];
  
    [HTTPURL uploadFileWithPath:HKPublicFilePath
                       fileName:nil
                         params:@{@"token" : WMglobalUser().token?:@""} data:data success:^(NSURLSessionDataTask *task, NSDictionary *successUrl) {
        [[HKLoadingView loadingView] hideLoading];
        NSDictionary *dataDic = KSSAFE_CAST(successUrl[@"data"], NSDictionary) ? :@{};
        
        NSString *encodeString = [[dataDic mj_JSONString] ks_URLEncodedString];
        NSString *jsString = [NSString stringWithFormat:@"javascript:recordFinishCallback(\"%@\")", encodeString];
        [self.wkWebView evaluateJavaScript:jsString completionHandler:^(id _Nullable data, NSError * _Nullable error) {
        }];
    } failure:^(NSURLSessionDataTask *task,NSError *error) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [[HKToastView sharedToastView] showToast:error.domain];
        });
        [[HKLoadingView loadingView] hideLoading];
    }];
}

- (void)clearCache {
    NSSet *websiteDataTypes = [WKWebsiteDataStore allWebsiteDataTypes];
    //// Date from
    
    NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
    
    //// Execute
    
    [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{
        
    }];
}

- (HKCalendarAndLocalNotificationHandler *)calenddarAndLocationNotificationHandler {
    if (!_calenddarAndLocationNotificationHandler) {
        _calenddarAndLocationNotificationHandler = [HKCalendarAndLocalNotificationHandler new];
    }
    return _calenddarAndLocationNotificationHandler;
}
//
//- (HKAvVideoRecorder *)recorder {
//    if (!_recorder) {
//        _recorder = [HKAvVideoRecorder new];
//        WS
//        [_recorder setToHasFinishRecordBlock:^{
//            SS
//            [self uploadRecordFile];
//        }];
//    }
//    return _recorder;
//}

- (HKScriptMessageDelegate *)scripteDelegate {
    if (!_scripteDelegate) {
        _scripteDelegate = [[HKScriptMessageDelegate alloc] initWithDelegate:self];
    }
    return _scripteDelegate;
}

- (UINavigationController *)keyNavi {
    return [AppDelegate appDelegate].keyNavi;
}

- (UIViewController *)currentViewController {
    return [self keyNavi].viewControllers.lastObject;
}

- (NSArray<NSString *> *)types {
    return @[(__bridge NSString *) kUTTypeContent,
                            (__bridge NSString *) kUTTypeData,
                            (__bridge NSString *) kUTTypePackage,
                            (__bridge NSString *) kUTTypeDiskImage,
                            @"com.apple.iwork.pages.pages",
                            @"com.apple.iwork.numbers.numbers",
                            @"com.apple.iwork.keynote.key"];
//    return @[@"com.microsoft.powerpoint.ppt",
//             @"com.microsoft.word.doc",
//             @"com.microsoft.excel.xls",
//             @"com.microsoft.powerpoint.pptx",
//             @"com.microsoft.word.docx",
//             @"com.microsoft.excel.xlsx",
//             @"public.avi",
//             @"public.3gpp",
//             @"public.mpeg-4",
//             @"com.compuserve.gif",
//             @"public.jpeg",
//             @"public.png",
//             @"public.plain-text",
//             @"com.adobe.pdf"];
    
}

- (void)createDocumentPickerWithTypes:(NSArray<NSString *> *)types {
    _documentPicker = [[UIDocumentPickerViewController alloc] initWithDocumentTypes:types inMode:UIDocumentPickerModeOpen];
    _documentPicker.delegate = self;
    _documentPicker.modalPresentationStyle = UIModalPresentationFullScreen;
    if (@available(iOS 13.0, *)) {
        _documentPicker.shouldShowFileExtensions = YES;
    } else {
        // Fallback on earlier versions
    }
}

- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentsAtURLs:(NSArray <NSURL *>*)urls {
    BOOL fileUrlAuthozied = [urls.firstObject startAccessingSecurityScopedResource];
    if (!fileUrlAuthozied) return;
    NSFileCoordinator *fileCoordinator = [[NSFileCoordinator alloc] init];
           NSError *error;
    __block BOOL isContain = YES;
    [urls enumerateObjectsUsingBlock:^(NSURL * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSString *sufix = [NSString stringWithFormat:@".%@",obj.pathExtension];
        if (![self.limitTypes containsObject:sufix]){
            isContain = NO;
        }
    }];
    if (!isContain){
        [[HKToastView sharedToastView] showToast:@"上传文件格式不正确"];
        return;
    }
    
    [fileCoordinator coordinateReadingItemAtURL:urls.firstObject options:0 error:&error byAccessor:^(NSURL *newURL) {
        NSLog(@"%@",newURL);
        //读取文件
        NSError *error = nil;
        NSData *fileData = [NSData dataWithContentsOfURL:newURL options:NSDataReadingMappedIfSafe error:&error];
        if (fileData != nil) {
            [self uploadFile:fileData fileName:newURL.pathComponents.lastObject];
        }
    }];
}

- (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller {
    
}

- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url {
}

- (void)interruptionBegan {
    
}

#pragma mark - 重定向
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
    if ([navigationResponse.response isKindOfClass:[NSHTTPURLResponse class]]) {
        NSHTTPURLResponse *httpResp = (NSHTTPURLResponse *)navigationResponse.response;
        NSInteger statusCode = httpResp.statusCode;
        NSString *newRequestUrl = httpResp.allHeaderFields[@"Location"];
        NSString *redirectUrl = httpResp.allHeaderFields[@"redirectUrl"];
        self.hasFinishLoading = YES;
        if (self.finishBlock) {
            self.finishBlock(YES);
        }
        // 302 重定向
        if (statusCode >= 300 && statusCode < 400 && redirectUrl && newRequestUrl) {
            //记录下重定向之前的url, 不要显示错误界面
            self.redirectUrl = redirectUrl;
            //这里cancel掉, 然后直接load新的url
            decisionHandler(WKNavigationResponsePolicyCancel);
            _request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:newRequestUrl] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
            [self.wkWebView loadRequest:_request];
            return;
        }
    }
    decisionHandler(WKNavigationResponsePolicyAllow);
}

//不要显示错误界面
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    //如果是重定向的url,这里 return 掉, 不要显示错误界面
    if (self.redirectUrl.length > 0 && error.userInfo && [error.userInfo objectForKey:@"NSErrorFailingURLStringKey"]) {
        NSString *failingURLString = [NSString stringWithFormat:@"%@", error.userInfo[@"NSErrorFailingURLStringKey"]];
        if ([self.redirectUrl isEqualToString:failingURLString]) {
            self.redirectUrl = nil;
            return;
        }
    }
}

//页面加载完成
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    self.redirectUrl = nil;
}

@end
